package com.winston.sab;


import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

public class PopupDialogAction extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        // Commands to execute
        String[] commands = {
                "go env -w CGO_ENABLED=0",
                "go env -w GOOS=linux",
                "go env -w GOARCH=amd64",
                "go build -o ./bin/server-agent main.go"
        };

        StringBuilder output = new StringBuilder();
        try {
            Project project = event.getProject();
            if (project == null) {
                Messages.showErrorDialog("No active project found!", "Error");
                return;
            }

            String projectBasePath = project.getBasePath();
            assert projectBasePath != null;
            File workingDir = new File(projectBasePath);
            for (String command : commands) {
                ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", command);

                // 设置环境变量
                builder.environment().put("PATH", System.getenv("PATH") + ":/usr/local/go/bin");
                builder.directory(workingDir);
                builder.redirectErrorStream(true);
                Process process = builder.start();

                // Read the command output
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
                reader.close();

                // Wait for the command to finish
                process.waitFor();
            }

            // Show output in a popup
            Messages.showInfoMessage(output.toString(), "Command Output");

        } catch (Exception ex) {
            Messages.showErrorDialog("Failed to execute commands: " + ex.getMessage(), "Error");
        }
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        // Set the availability based on whether a project is open
        Project project = e.getProject();
        e.getPresentation().setEnabledAndVisible(project != null);
    }
}

